﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Data.Objects.DataClasses;
using System.Data.Objects;

namespace JingQiao.Ads.Infrastructure.Data.EF.Repository
{
    using Domain.Model;
    using Domain.Model.DomainObject;
    using Domain.Model.Repository;

    public abstract class BaseRepository<TEntity> : IRepository<TEntity>
    {
        protected readonly AdsContext _context;
        private static readonly object lockPad = new object()

        protected BaseRepository(IContext context)
        {
            Check.Argument.IsNotNull(context, "context");
            this._context = context as AdsContext;
        }

        public virtual void Add(TEntity entity)
        {
            Check.Argument.IsNotNull(entity, "entity");
            this._context.Insert(entity);
        }

        public virtual void Remove(TEntity entity)
        {
            Check.Argument.IsNotNull(entity, "entity");
            this._context.Delete(entity);
        }

        protected static PagedResult<T> BuildPagedResult<T>(IEnumerable entities, int total)
        {
            return new PagedResult<T>(entities.Cast<T>(), total);
        }

        public AdsContext ContextContainer
        {
            get 
            { 
                if (this._context.Connection.State == System.Data.ConnectionState.Open)
                {
                    return this._context;
                }

                lock (lockPad)
                {
                    if (this._context.Connection.State != System.Data.ConnectionState.Open)
                    {
                        this._context.Connection.Open();
                    }
                }

                return this._context;
            }
        }
    }
}
